package com.wy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.model.entity.Role;
import com.wy.model.entity.UserRole;
import com.wy.model.vo.AssignRoleVo;
import com.wy.model.vo.RoleQueryVo;
import com.wy.system.mapper.RoleMapper;
import com.wy.system.mapper.UserRoleMapper;
import com.wy.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

  @Autowired
  private UserRoleMapper userRoleMapper;

  //条件分页查询
  @Override
  public IPage<Role> selectPage(Page<Role> pageParam, RoleQueryVo roleQueryVo) {
    IPage<Role> pageModel = baseMapper.selectPage(pageParam, roleQueryVo);
    return pageModel;
  }
  //获取用户的角色数据
  @Override
  public Map<String, Object> getRoleByUserId(Integer userId) {
    //获取所有角色
    List<Role> roles = baseMapper.selectList(null);
    //根据用户id查询，已经分配的角色
    QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
    wrapper.eq("user_id",userId);
    List<UserRole> userRolesList = userRoleMapper.selectList(wrapper);
    //从userRoles集合获取所有角色id
    List<Integer> userRoleIds = new ArrayList<>();
    for (UserRole userRole : userRolesList) {
      int roleId = userRole.getRoleId();
      userRoleIds.add(roleId);
    }
    //封装到map集合
    Map<String, Object> returnMap = new HashMap<>();
    returnMap.put("allRoles",roles);//所有角色
    returnMap.put("userRoleIds",userRoleIds);//用户分配角色id集合
    return returnMap;
  }

  //用户分配角色
  @Override
  public void doAssign(AssignRoleVo assignRoleVo) {
    //根据用户id删除之前分配的角色
    QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
    wrapper.eq("user_id",assignRoleVo.getUserId());
    userRoleMapper.delete(wrapper);

    //获取所有角色id，添加角色用户关系表
    //角色id列表
    List<Integer> roleIdList = assignRoleVo.getRoleIdList();
    for (Integer roleId : roleIdList) {
      UserRole userRole = new UserRole();
      userRole.setUserId(assignRoleVo.getUserId());
      userRole.setRoleId(roleId);
      userRoleMapper.insert(userRole);
    }
  }
}
